﻿namespace ChinaUnicom.Converters
{
    using System;
    using System.Globalization;
    using System.Windows;
    using System.Windows.Data;

    public class TrafficConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string tag = "Byte";
            double length = (long)value / 1.0;

            if (length > 1024 * 1024)
            {
                tag = "MB";
                length /= (1024.0 * 1024.0);
            }
            else if (length > 1024)
            {
                tag = "KB";
                length /= 1024.0;
            }

            return string.Format("{0:F3} {1}", length, tag);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string strValue = value as string;

            string[] strItems = strValue.Split(new[] { ' ' });
            if (strItems.Length == 2)
            {
                double length;
                if (double.TryParse(strItems[0], out length))
                {
                    return length;
                }
            }

            return DependencyProperty.UnsetValue;
        }
    }

}
